package com.yxjx.duoxue.comment;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.comment.DetailedCommentActivity.MyListAdapter;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnLoadListener;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnRefreshListener;
import com.yxjx.duoxue.datamodel.DMComment;
import com.yxjx.duoxue.my.FavouriteCoursesActivity;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;

public class MyCommentsActivity extends BaseActionBarActivity implements
		OnRefreshListener, OnLoadListener {

	public static final int MSG_LOAD_ALL = 1;
	public static final int MSG_LOAD_MORE = 2;
	private AutoListView mList;
	private ArrayList<DMComment> mAllComments = new ArrayList<DMComment>();
	private MyListAdapter mAdapter;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_detail_comment);
		customizeActionBarTitle("我的点评");
		
		mList = (AutoListView) findViewById(R.id.list);
		mAdapter = new MyListAdapter();
		mList.setAdapter(mAdapter);
		mList.setOnRefreshListener(this);
		mList.setOnLoadListener(this);
		showLoading(true);
		doLoadComments();
		
	}
	
	private void doLoadComments() {
		new Thread(new Runnable() {
			@Override
			public void run() {
			    ArrayList<DMComment> comments = loadComments();
				Message msg = mHandler.obtainMessage(MSG_LOAD_ALL, comments);
				mHandler.sendMessage(msg);
			}
		}).start();
	}
	
	private void doLoadMoreComments() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				ArrayList<DMComment> moreComments = loadMoreComments();
				Message msg = mHandler.obtainMessage(MSG_LOAD_MORE, moreComments);
				mHandler.sendMessage(msg);
			}
		}).start();
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			ArrayList<DMComment> comments = (ArrayList<DMComment>) msg.obj;
			switch (msg.what) {
			case MSG_LOAD_ALL:
				mAllComments = comments;
				updateEmptyIfNeeded();
				mAdapter.notifyDataSetChanged();
				showLoading(false);
				mList.onRefreshComplete();
				resetScroll();
				break;
			case MSG_LOAD_MORE:
				mAllComments.addAll(comments);
				updateEmptyIfNeeded();
				mAdapter.notifyDataSetChanged();
				mList.onLoadComplete();
				break;
			default:
				break;
			}
			mList.setResultSize(comments == null ? 0 : comments.size());
			
		}
	};
	
	private void showLoading(boolean show) {
		findViewById(R.id.loading).setVisibility(show ? View.VISIBLE : View.GONE);
		findViewById(R.id.root).setVisibility(show ? View.INVISIBLE : View.VISIBLE);
	}
	
	private ArrayList<DMComment> loadComments() {
		JSONObject params = new JSONObject();
		try {
			params.put("startIndex", "1");
			params.put("count", 20);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return loadCommentsByParams(params);
	}

	class MyListAdapter extends BaseAdapter {
		public static final int TYPE_RECORD = 0;
		public static final int TYPE_COUNT_TOTAL = 1;

		@Override
		public int getCount() {
			return mAllComments == null ? 0 : mAllComments.size();
		}
		
		@Override
		public int getItemViewType(int position) {
			return TYPE_RECORD;
		}
		
		@Override
		public int getViewTypeCount() {
			return TYPE_COUNT_TOTAL;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (getItemViewType(arg0) == TYPE_RECORD) {
				if (arg1 == null) {
					ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_my_comment_record_wrapper, null);
				} else {
					ret = arg1;
				}
				DMComment comment = mAllComments.get(arg0);
				MyCommentItemView itemView = (MyCommentItemView) ret.findViewById(R.id.commentItemView);
				itemView.setComment(comment);
			}
			return ret;
		}
		
	}

	private ArrayList<DMComment> loadMoreComments() {
		JSONObject params = new JSONObject();
		try {
			params.put("startIndex", mAllComments.size() + 1);
			params.put("count", 20);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return loadCommentsByParams(params);
	}
	
	// 0默认查询所有评论,1课程评论,2活动评论,3学校评论,4老师评论。
	private String convertType(int type) {
		if (type == Yx.TYPE_ITEM_SCHOOL) {
			return "3";
		} else if (type == Yx.TYPE_ITEM_COURSE) {
			return "1";
		} else {
			return "0";
		}
	}
	
	private ArrayList<DMComment> loadCommentsByParams(JSONObject params) {
		UserLoginResponse ulRsp = UserLoginResponse.getInstance(getApplicationContext());
		if (ulRsp == null) {
			return null;
		}
		
		ArrayList<DMComment> comments = new ArrayList<DMComment>();
		try {
			comments = (ArrayList<DMComment>) UserReg.getMyComments(ulRsp, params, MyCommentsActivity.this);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return comments;
	}

	@Override
	public void onLoad() {
		doLoadMoreComments();
	}

	@Override
	public void onRefresh() {
		doLoadComments();
	}
	
	private void resetScroll() {
		mList.post(new Runnable() {
			
			@Override
			public void run() {
				mList.setSelection(0);
			}
		});
	}

	private void updateEmptyIfNeeded() {
		if (mAllComments == null || mAllComments.size() == 0) {
			findViewById(R.id.root).setVisibility(View.INVISIBLE);
			findViewById(R.id.empty).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.root).setVisibility(View.VISIBLE);
			findViewById(R.id.empty).setVisibility(View.INVISIBLE);
		}
	}
	
	public void toFind(View view) {
		UIHelper.LoadingActivity(this,
				new Intent(getApplicationContext(),
						CourseListActivity.class));
		finish();
	}
}
